<?php
/**
 * Created by PhpStorm.
 * User: lcz
 * Date: 2018/8/1
 * Time: 11:12
 */

namespace app\common\model;

use think\Model;
use think\Request;

class Baokim extends Model {
	//帐户配置
	public $EMAIL_BUSINESS = 'luhaojia@viettime.shop';//Email Bảo kim
	public $MERCHANT_ID = '33958';                // Mã website tích hợp 代码网站集成
	public $SECURE_PASS = 'd05c0c9207b78da2';   // Mật khẩu 密码
	
	// 配置集成帐户
	public $API_USER = '5000mua';  //API USER
	public $API_PWD = '0xmt33RuwNEo2nbqeQ6LDz19XgyfB';       //API PASSWORD
	public $PRIVATE_KEY_BAOKIM = '-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDxoD0KfPfS+Aq4
Cbe8rV1KYhi/Oasvc4jhF1fDzFU6E1b7J/g2kJV975ygfwwbX5FAZOLdwIVlG1Ug
RaZ4rG3RrZfWLQNnzCgcz8HQBVFnO1JTCphRH5KNr5wlwgmrYEw+Tzx8sVXN5TWT
QzNN89BINxYS+wLpHbqcOaTM2HrhWUgrAKPGixPEnupMZts1sYuKi2yB0fy84oAu
U7zSzk2IuIxOiiAOKEM0pHECseOmmx771yNBM/x8q00KHIx4jG+RO1kzuqGdAAVc
vm5BpyFb+4P1v/b+79c5h1BCuRTil9GdvMeSudPmRbSRqqaBuhpisUV1+bgiJSX2
gjBA7llDAgMBAAECggEBAITw3uTYYRoIMw2S+y6qS/vTAT6lIhSXgqYly7oEwJeV
cHP7R8vtvPJvVUPQ4v5klGxTlabgeARrB2kcKT2X0UxeMH48gfUoFKHVhRNI+cLM
lrztxWRM9LtT9ZuoqN1LvGdD/Um14DnKdLGzdZTcIqq49EI5LR7JppSx+oRiTymQ
fjoivMRPfjvmX4WwsYo9c/sP7XUmfId6BUQdiAfbWhVFAWhP4LgfzY7yt/VKjM7s
Mmblm2rqCQhjqCckTN/gTJzxAVGAQAf4Upp5J3ExiPQTtZUsaTtqbzvIl0sIUM4D
eBz9k116Rr+U7tuN42tKNvB61pwYlch2m8RGCbRJgqECgYEA/ApFOSPRE/gkKvMs
POqZAZepHWUuHsuuz2h6sIIrT6+NPB6zgwqJ8ueRWPM6QRBTDTGX8IFXxF8MNpgD
RyhigmlWYvK34ncBPnjiZQuvG8eWAjVpAIzRtTcS3RAD+64Neca1esS52sGrgBp8
+Hzl39mIVKPxsWv3HsZ8FAY0t6kCgYEA9WwUx+O3Ef4PLWSdhbGF26mPKw1VZ1XX
zSDCtiS8l+vG3LyhQlKplxf7NEnk3rX3oo8Mu0W/7zo6bLcatGv40lMQJ4zsahfA
MkKHPPNlNrZQZROazeTHoDY6GOSV3G4A0lH7nIbK7+LRrb0a29Tv7hE/fugaVHz7
Z+D93/Nr7QsCgYEAxqwh3OTKzn7vo5uD55DVg1fVSwKS1FuiNIQbEj/JfErZfeaF
gmowS3UWMZOo+9iuXtwU9NRAJt71daNmEhVXcY0vN1g0cyNzq5cGfrgzFCbDrIIF
fxWByOLcz7zsJtwQa0mjjF6+Uh4P3i8DC60IVufWe0GwJzb/2RaEgBRUQeECgYEA
lpETgrra4uf6ScATwCT0WZqCIkiQ38/TkJ6LtpF9PrtBCsWTLYxnTTJCRIcdKeF7
priad/5Hza3skCwZ7xzaz7Z0D7+ufzxJBsy4CZXNv65ETm6jp7O3ITyDkigTJOQ8
DsyLUDGGKXv/ZdbBtqLB/E2KpgIhvTncR5PKTW4bBZcCgYAabUSwxoPfNuvGMnij
1PegwZL5Rvs5zFUOEe7osj0jtjnWlKcbqjOysyFjiWGqX3hmWSMoBHR9NWHiUKnB
tdQiD64Pj3BEldhjrBrGioRPzhOUH/lYEWy36oOgsQcmVcNSw4VP0io6NPH2VZbr
7spP+APsaKhXONER0g1UxfZk1g==
-----END PRIVATE KEY-----';
	
	public $BAOKIM_API_SELLER_INFO = '/payment/rest/payment_pro_api/get_seller_info';
	public $BAOKIM_API_PAY_BY_CARD = '/payment/rest/payment_pro_api/pay_by_card';
	public $BAOKIM_API_PAYMENT = '/payment/order/version11';
	
	//正式地址
	public $BAOKIM_URL = 'https://www.baokim.vn';
	
	//测试地址
	// const('BAOKIM_URL','http://baokim.dev');
	// const('BAOKIM_URL','http://kiemthu.baokim.vn');
//	public $BAOKIM_URL = 'https://sandbox.baokim.vn';
	
	//Phương thức thanh toán bằng thẻ nội địa 本地卡的付款方式
	public $PAYMENT_METHOD_TYPE_LOCAL_CARD = 1;
	//Phương thức thanh toán bằng thẻ tín dụng quốc tế 使用国际信用卡付款
	public $PAYMENT_METHOD_TYPE_CREDIT_CARD = 2;
	//Dịch vụ chuyển khoản online của các ngân hàng 网上银行转账服务
	public $PAYMENT_METHOD_TYPE_INTERNET_BANKING = 3;
	//Dịch vụ chuyển khoản ATM ATM转账服务
	public $PAYMENT_METHOD_TYPE_ATM_TRANSFER = 4;
	//Dịch vụ chuyển khoản truyền thống giữa các ngân hàng 银行之间的传统银行转账服务
	public $PAYMENT_METHOD_TYPE_BANK_TRANSFER = 5;
	
	//成功返回的数据
	// https://_/success?created_on=1532571018&customer_address=&customer_email=qq%40qq.com&customer_location=&customer_name=wu&customer_phone=841871824803&fee_amount=0&merchant_email=dev.baokim%40bk.vn&merchant_id=647&merchant_location=&merchant_name=Dev+Hieu+Nguyen&merchant_phone=016885201968&net_amount=10000&order_id=1532680772&payment_type=2&total_amount=10000.00&transaction_id=3E960CF79A928&transaction_status=13&checksum=586623A90EB075E6E429DC3361AB97A6A9AC066A
	//创建付款URL
	public function createRequestUrl($data)
	{
		$order_id = $data['order_id'];
		$total_amount = $data['total_amount'];
		$url_success = Request::instance()->domain().url('index/pay/baokimSuccess');
		$url_cancel = Request::instance()->domain().url('index/pay/cancel');
		$currency = 'VND'; // USD
		// Mảng các tham số chuyển tới baokim.vn
		$params = array(
			'merchant_id'		=>	strval($this->MERCHANT_ID),
			'order_id'			=>	strval($order_id),
			'business'			=>	strval($this->EMAIL_BUSINESS),
			'total_amount'		=>	strval($total_amount),
			'shipping_fee'		=>  strval('0'),
			'tax_fee'			=>  strval('0'),
			'order_description'	=>	strval('Thanh toán đơn hàng từ Website với mã đơn hàng ' . $order_id),
			'url_success'		=>	strtolower($data['success_url']),
			'url_cancel'		=>	strtolower($data['cancel_url']),
			'url_detail'		=>	strtolower(''),
			'payer_name'		=>  strval($data['payer_name']),
			// 'payer_name'		=>  "Truong Hoang Duong",
			'payer_email'		=> 	strval($data['payer_email']),
			// 'payer_email'		=> 	"duongga@gmail.com",
			'payer_phone_no'	=> 	strval($data['payer_phone_no']),
			// 'payer_phone_no'	=> 	"0976098886",
			'shipping_address'  =>  strval($data['shipping_address']),
			// 'shipping_address'  =>  "Bai Chay, Ha Long",
			'currency' => strval($currency),
		
		);
		ksort($params);
		
		$params['checksum']=hash_hmac('SHA1',implode('',$params),$this->SECURE_PASS);
		
		//Kiểm tra  biến $redirect_url xem có '?' không, nếu không có thì bổ sung vào
		$redirect_url = $this->BAOKIM_URL . $this->BAOKIM_API_PAYMENT;
		if (strpos($redirect_url, '?') === false)
		{
			$redirect_url .= '?';
		}
		else if (substr($redirect_url, strlen($redirect_url)-1, 1) != '?' && strpos($redirect_url, '&') === false)
		{
			// Nếu biến $redirect_url có '?' nhưng không kết thúc bằng '?' và có chứa dấu '&' thì bổ sung vào cuối
			$redirect_url .= '&';
		}
		
		// Tạo đoạn url chứa tham số
		$url_params = '';
		foreach ($params as $key=>$value)
		{
			if ($url_params == '')
				$url_params .= $key . '=' . urlencode($value);
			else
				$url_params .= '&' . $key . '=' . urlencode($value);
		}
		return $redirect_url.$url_params;
	}
	
	
	public function verifyResponseUrl($url_params = array())
	{
		if(empty($url_params['checksum'])){
			echo "invalid parameters: checksum is missing";
			return FALSE;
		}
		
		$checksum = $url_params['checksum'];
		unset($url_params['checksum']);
		
		ksort($url_params);
		
		if(strcasecmp($checksum,hash_hmac('SHA1',implode('',$url_params),$this->SECURE_PASS))===0)
			return TRUE;
		else
			return FALSE;
	}
	
	public function test(){
		$data = [
			//订单信息
			'order_id' => '', //Y 订单代码
			'business' => '', //Y 卖家帐号邮箱
			'total_amount' => '', //Y 订单总额
			'order_description' => '', //N 订单说明
			'shipping_fee' => '', //N 运费，默认值：0
			'tax_fee' => '', //N 税，默认：0
			'url_cancel' => '', //N 取消付款时，网址重定向
			'url_success' => '', //N 付款成功后网址重定向
			'url_detail' => '', //N 查看订单项网址
			
			//买家信息
			'payer_name' => '', //Y 买方名称
			'payer_email' => '', //Y 买家的电子邮件
			'payer_phone_no' => '', //Y 买家电话号码
			'payer_address' => '', //N 买方地址，格式为：ADDRESS | CITY
			'message' => '', //N 购买消息
			
			//付款方式信息
			'bank_payment_method_id' => '', //Y 银行付款方式代码
			'transaction_mode_id' => '', //N 1：直接/ 2：安全，默认：1
			'escrow_timeout' => '', //N 保留的天数（如果付款安全），默认值：0
			'mui' => '', //N 	界面显示指南充值（包括3种模式：充电/基准/ iframe），默认：充电
		];
	}
}
